<template>
  <MglMap
    :accessToken="accessToken"
    :mapStyle="mapOptions.mapStyle"
    :zoom="mapOptions.zoom"
    :maxBounds="mapOptions.maxBounds"
    :center="mapOptions.center"
    @load="onMapLoaded"
    :dragRotate="false"
    :doubleClickZoom="false"
    :bearing="-23"
    class="map"
  >
    <!-- 标记层组件 -->
    <MapMarkers ref="markers" @refreshData="refreshData" />
    <!-- 车辆轨迹组件 -->
    <MapTracks />

    <!-- wmsLayer -->
    <MglRasterLayer
      :sourceId="wmsSource.id"
      :source="wmsSource.source"
      :layer="wmsLayer"
      :layerId="wmslayerId"
    ></MglRasterLayer>
    <!-- <MglRasterLayer
      v-for="(item,index) in wmsArrs"
      :sourceId="item.wmsSource.id"
      :source="item.wmsSource.source"
      :layer="item.wmsLayer"
      :layerId="item.wmslayerId"
      :key="index"
    ></MglRasterLayer>-->
    <MglGeojsonLayer
      ref="geoJsonlayer"
      :sourceId="geoJsonSource.id"
      :source="geoJsonSource.source"
      :layerId="geoJsonlayerId"
      :layer="geoJsonLayer"
    ></MglGeojsonLayer>

    <!-- 区域mask -->
    <div>
      <!-- <MglGeojsonLayer
        :sourceId="maskSource.id"
        :source="maskSource.source"
        :layer="maskLayer"
        :layerId="masklayerId"
      />-->
    </div>

    <!-- 控制面板 -->
    <!-- <RtPanel
      :markersArr="markersArr"
      :typesArr="typesArr"
      :treeData="treeData"
      v-on:floor="floorsNum($event)"
      v-on:doorsGeo="doorsData($event)"
      v-on:mapOptions="mapOp($event)"
      v-on:typesArr="tpArr($event)"
      v-on:markersArr="mkArr($event)"
      v-on:carTracks="carTas($event)"
      v-on:indoorArrs="indoorArr($event)"
      v-on:newScene="sceneStr($event)"
      v-on:testArrs="testGeo($event)"
    ></RtPanel>-->

    <!-- <LtPanel v-if="scene=='indoors'" v-on:floor="floorsNum($event)"></LtPanel> -->
    <BtnPanel
      @isDistance="isDistance"
      @rmDistance="rmDistance"
      @rmPolygon="rmPolygon"
      @areaDivision="areaDivision"
      @areaDanger="areaDanger"
    ></BtnPanel>
    <!-- <SelectPanel @changeMapOptions="changeMapOptions" ref="panel"></SelectPanel> -->

    <!-- 测距 -->
    <Ranging></Ranging>
    <!-- 划区 -->
    <!-- <Division></Division> -->
    <!-- 高风险区 -->
    <!-- <AddPolygon @polyDrawEnd="polyDrawEnd"></AddPolygon> -->
    <!-- 路线轨迹数据 -->
    <MapLinesPane @isShowWms="isShowWms" @isShowSatellite="isShowSatellite"></MapLinesPane>
    <!-- 区域文本 -->
    <MapAreaText></MapAreaText>
    <!-- 测试android交互 -->
    <div class="android-test">
      <!-- <el-button @click="callAndroid()">{{callback}}</el-button> -->
      <!-- <el-button @click="addDanger()">添加高风险区域</el-button> -->
    </div>
    <!-- 地图控制组件 -->
    <!-- <MglNavigationControl position="top-left" />
    <MglFullscreenControl position="top-left" />-->
  </MglMap>
</template>
<script>
/* eslint-disable */
import "@/assets/iconfont/iconfont.css";
import Mapbox from "mapbox-gl";
import {
  MglMap,
  MglGeojsonLayer,
  MglMarker,
  MglPopup,
  MglRasterLayer,
  MglVideoLayer,
  MglNavigationControl,
  MglFullscreenControl,
  MglScaleControl
} from "vue-mapbox";
import MapboxLanguage from "@mapbox/mapbox-gl-language";
import MapboxDirections from "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions";
import "@mapbox/mapbox-gl-directions/dist/mapbox-gl-directions.css";
import _ from "lodash";
import * as turf from "@turf/turf";
import { mapGetters } from "vuex";

//地图组件导入
import MapMarkers from "./mapparts/MapMarkers.vue";
import MapTracks from "./mapparts/MapTracks.vue";
import MapLinesPane from "./mapparts/MapLinesPane";
import MapAreaText from "./mapparts/MapAreaText";

//控制面板组件
// import RtPanel from "./controlpanel/RtPanel";
// import LtPanel from "./controlpanel/LtPanel";
import SelectPanel from "./controlpanel/SelectPanel";
import BtnPanel from "./controlpanel/BtnPanel";
import Ranging from "./controlpanel/Ranging";
import Division from "./controlpanel/Division";
import AddPolygon from "./controlpanel/AddPolygon";

//模拟室内图层
const mapgeoJson = require("@/assets/basfgis/mapgeo.json");

import bus from "./eventBus";

//测距默认line数据
var linestring = {
  type: "Feature",
  geometry: {
    type: "LineString",
    coordinates: []
  }
};

const wmsArr = [
  {
    wmsSource: {
      id: "wms-init",
      source: {
        type: "raster",
        tiles: [
          "http://116.236.24.22:18980/geoserver/BACH/wms?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=BACH:uu"
        ],
        tileSize: 256
      }
    },
    wmsLayer: {
      type: "raster",
      paint: {
        "raster-opacity": 1
      }
    },
    wmslayerId: "wms-init-layer"
  },
  {
    wmsSource: {
      id: "wms-1F",
      source: {
        type: "raster",
        tiles: [
          "http://59.80.30.176:8089/geoserver/BACH/wms?service=WMS&version=1.1.0&request=GetMap&layers=BACH:1F_shap&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png"
        ],
        tileSize: 256
      }
    },
    wmsLayer: {
      type: "raster",
      paint: {
        "raster-opacity": 0
      }
    },
    wmslayerId: "wms-1F-layer"
  },
  {
    wmsSource: {
      id: "wms-init",
      source: {
        type: "raster",
        tiles: [
          "http://59.80.30.176:8089/geoserver/BACH/wms?service=WMS&version=1.1.0&request=GetMap&layers=BACH:2F_shap&bbox={bbox-epsg-3857}&width=256&height=256&srs=EPSG:3857&format=image/png"
        ],
        tileSize: 256
      }
    },
    wmsLayer: {
      type: "raster",
      paint: {
        "raster-opacity": 0
      }
    },
    wmslayerId: "wms-2F-layer"
  }
];

export default {
  components: {
    MglMap,
    MapboxLanguage,
    MglGeojsonLayer,
    MglMarker,
    MglPopup,
    MglRasterLayer,
    MglVideoLayer,
    MapMarkers,
    MapTracks,
    // RtPanel,
    // LtPanel,
    SelectPanel,
    Ranging,
    Division,
    AddPolygon,
    BtnPanel,
    MapLinesPane,
    MapAreaText,
    MglNavigationControl,
    MglFullscreenControl
  },
  data() {
    return {
      accessToken:
        "pk.eyJ1IjoiamltbXkwMDkiLCJhIjoiY2swNHl2M3owMGl2bzNja2F3emk0OWxvaiJ9.cIYfwmmCkLoyQseAEI6UzQ", // your access token. Needed if you using Mapbox maps
      mapOptions: {
        mapStyle: "mapbox://styles/mapbox/light-v10",
        center: [121.46960637043458, 30.7913819151417], //[121.52792994063162, 31.21669976798036]
        // maxBounds: [[121.45928724454387, 30.78519614578238], [121.47992549632482, 30.797567286556315]],
        zoom: 16.737981956944786 //16.737981956944786
      },
      geoArrs: [],
      doorsArr: [],
      markersArr: [],
      scene: "",
      typesArr: [],
      floors: "",
      carTracks: [
        [121.52792994063162, 31.21669976798036],
        [121.5278303783237, 31.21704536401083],
        [121.52777766886766, 31.217220665862243],
        [121.52852145787409, 31.217476105120852],
        [121.52918325439282, 31.217736552281835],
        [121.52923596385051, 31.21787178417837],
        [121.52883771461677, 31.21863809460659]
      ],
      treeData: [],
      options: [],
      //wms-test
      wmsSource: {
        id: "wms-init",
        source: {
          type: "raster",
          tiles: [
            "http://116.236.24.22:18980/geoserver/BACH/wms?bbox={bbox-epsg-3857}&format=image/png&service=WMS&version=1.1.1&request=GetMap&srs=EPSG:3857&transparent=true&width=256&height=256&layers=BACH:uu"
          ],
          tileSize: 256
        }
      },
      wmsLayer: {
        type: "raster",
        paint: {
          "raster-opacity": 1
        }
      },
      wmslayerId: "wms-test-layer",
      wmsArrs: wmsArr,
      wmsShow: true,
      satelliteShow: false,
      geoJsonSource: {
        id: "geojson",
        source: {
          type: "geojson",
          data: {
            type: "FeatureCollection",
            features: []
          }
        }
      },
      geoJsonLayer: {
        type: "line",
        paint: {
          "line-width": 2,
          "line-color": "#111"
        }
      },
      geoJsonlayerId: "geojson",
      //遮罩层模拟数据
      maskSource: {
        id: "mask-init",
        source: {
          type: "geojson",
          data: {
            type: "Feature",
            geometry: {
              type: "Polygon",
              //[[121.4615526907096, 30.790186199605543], [121.4705778645278, 30.79559605429958]],
              //bounds:LngLatBounds(LngLat(121.45986980354184, 30.789292109733125), LngLat(121.47223475274387, 30.796703878795256))
              coordinates: [
                [
                  [121.46242658520003, 30.79393178321041],
                  [121.46731256625884, 30.79570619463575],
                  [121.46917310113832, 30.79193432728799],
                  [121.46419462802294, 30.79015560326901],
                  [121.46242658520003, 30.79393178321041]
                ]
              ]
            }
          }
        }
      },
      maskLayer: {
        type: "fill",
        paint: {
          "fill-color": "#000000",
          "fill-opacity": 0.8
        }
      },
      //       [
      //   [121.45986980354184, 30.796703878795256],
      //   [121.47223475274387, 30.796703878795256],
      //   [121.47223475274387, 30.789292109733125],
      //   [121.45986980354184, 30.789292109733125],
      //   [121.45986980354184, 30.796703878795256]
      // ]
      masklayerId: "mask-layer",
      videoSource: {
        id: "video-pop",
        source: {
          type: "video",
          urls: [
            "http://cdn001.newtouchwork.com/new-vedio_20190809175430986.mp4"
          ],
          coordinates: [
            [121.52747980616437, 31.21958060254574],
            [121.52753430064226, 31.219281267555868],
            [121.52777533390888, 31.219318908534902],
            [121.52769359219239, 31.219618243405517]
          ]
        }
      },
      videoLayer: {
        type: "raster"
      },
      videolayerId: "video-layer",
      //测距
      isRange: false,
      distance: "",
      distances: [],
      lnglatArr: [],
      finallnglats: [],
      dotsArr: [],
      addNew: false,
      //划区
      isDivision: false,
      //高风险
      isDanger: false,
      isDrawPoly: true,
      polygonLnglats: [],
      //android-test
      callback: "开始",
      count: 0
    };
  },

  beforeCreate() {},

  created() {
    // We need to set mapbox-gl library here in order to use it in template
    this.mapbox = Mapbox;
  },

  mounted() {
    window.callJsFun = this.callJsFun;
  },

  computed: {},

  methods: {
    onMapLoaded(event) {
      var map;
      map = event.map;
      this.asyncActions = event.component.actions;

      let lineNum = 0; //初始化测距次数

      //地图单击操作
      map.on(
        "click",
        _.debounce(
          e => {
            // console.log("event:" + e);
            let vm = this;

            //测距操作部分
            if (vm.isRange) {
              let lng = e.lngLat.lng;
              let lat = e.lngLat.lat;
              vm.lnglatArr.push([lng, lat]);
              // console.log(JSON.stringify(vm.lnglatArr));
              bus.$emit("lineDataArr", JSON.stringify(vm.lnglatArr));
              vm.dotsArr.push({
                type: "Feature",
                geometry: {
                  type: "Point",
                  coordinates: [lng, lat]
                }
              });
              if (vm.lnglatArr.length >= 2) {
                if (vm.addNew || vm.finallnglats.length == 0) {
                  vm.finallnglats.push({
                    type: "Feature",
                    geometry: {
                      type: "LineString",
                      coordinates: vm.lnglatArr
                    }
                  });
                  lineNum = vm.finallnglats.length - 1;
                  linestring.geometry.coordinates = vm.lnglatArr;
                  vm.distance = turf
                    .lineDistance(linestring, { units: "meters" })
                    .toFixed(1)
                    .toLocaleString();
                  vm.distances.push({ lineDis: vm.distance, coordinates: [] });
                  vm.addNew = false;
                } else if (!vm.addNew && vm.finallnglats.length > 0) {
                  // debugger
                  vm.finallnglats[lineNum]["geometry"]["coordinates"] =
                    vm.lnglatArr;
                  linestring.geometry.coordinates = vm.lnglatArr;
                  vm.distance = turf
                    .lineDistance(linestring, { units: "meters" })
                    .toFixed(1)
                    .toLocaleString();
                  vm.distances[lineNum]["lineDis"] = vm.distance;
                }
                vm.distances[lineNum]["coordinates"] = [
                  e.lngLat.lng,
                  e.lngLat.lat
                ];
                vm.$store.dispatch("distances/addDistances", vm.distances);
                vm.$store.dispatch("distances/addLines", vm.finallnglats);
              }
              vm.$store.dispatch("distances/addDots", vm.dotsArr);
            } else if (vm.isDivision) {
              let lng = e.lngLat.lng;
              let lat = e.lngLat.lat;
              let divlnglatObj = {
                zoom: map.getZoom(),
                center: [map.getCenter().lng, map.getCenter().lat],
                coordinates: [lng, lat],
                isDivs: true
              };
              vm.$store.dispatch("distances/addDivision", divlnglatObj);
            } else if (vm.isDanger && vm.isDrawPoly) {
              let lng = e.lngLat.lng;
              let lat = e.lngLat.lat;
              vm.lnglatArr.push([lng, lat]);
              vm.polygonLnglats.push([lng, lat]);
              vm.dotsArr.push({
                type: "Feature",
                geometry: {
                  type: "Point",
                  coordinates: [lng, lat]
                }
              });
              if (vm.lnglatArr.length >= 2) {
                vm.finallnglats.push({
                  type: "Feature",
                  geometry: {
                    type: "LineString",
                    coordinates: vm.lnglatArr
                  }
                });
                vm.$store.dispatch("distances/addLines", vm.finallnglats);
              }
              vm.$store.dispatch("distances/addDots", vm.dotsArr);
              vm.$store.dispatch("distances/addPolygon", vm.polygonLnglats);
            } else {
              return;
            }
          },
          300,
          { leading: true, trailing: false }
        )
      );

      //地图双击操作
      map.on("dblclick", e => {
        // console.log(e);
        let vm = this;
        if (vm.isRange) {
          vm.distances[lineNum]["coordinates"] = [e.lngLat.lng, e.lngLat.lat];
          vm.$store.dispatch("distances/addDistances", vm.distances);
          vm.lnglatArr = [];
          vm.addNew = true;
        }
      });

      //地图zoom操作
      map.on("zoom", e => {
        // console.log(map.getZoom())
        // console.table({ a: "10" });
      });

      //地图zoomend操作
      map.on("zoomend", e => {
        let vm = this;
        if (vm.isDivision) {
          let divlnglatObj = {
            zoom: map.getZoom(),
            center: [map.getCenter().lng, map.getCenter().lat],
            coordinates: this.$store.getters.divisionObj.coordinates,
            isDivs: true
          };
          vm.$store.dispatch("distances/addDivision", divlnglatObj);
        }
      });

      let language = new MapboxLanguage({ defaultLanguage: "zh" });
      map.addControl(language);

      //选取路线插件
      let directions = new MapboxDirections({
        accessToken: this.accessToken,
        unit: "metric",
        profile: "mapbox/driving"
      });
      // map.addControl(directions, 'top-left');
    },
    // 刷新
    refreshData() {
      this.$refs.panel.getDataList();
    },
    carTas(carRes) {
      this.carTracks = carRes;
    },
    floorsNum(floorRes) {
      this.floors = floorRes;
    },
    changeMapOptions(mapid) {
      let vm = this;
      vm.$http.get("mapboxmaplevel/selectById?mapid=" + mapid, null, res => {
        vm.geoJsonSource.source.id = "source_" + mapid;
        let mapoption = res.data;
        // debugger
        if (mapoption.center != "" && mapoption.zoom != "") {
          // 飞到中心点
          let options = {
            zoom: parseInt(mapoption.zoom),
            speed: 0.8,
            center: mapoption.center.split(",")
            // bearing:-23
          };
          vm.asyncActions.flyTo(options);
        }
        //切换数据源
        // if (mapoption.geojson == null) {
        //   vm.geoJsonSource.source.data = {
        //     type: 'FeatureCollection',
        //     features: []
        //   }
        //   return
        // }
        //vm.geoJsonSource.source.data = JSON.parse(mapoption.geojson)

        if (mapoption.level === "4" && mapoption.name === "1F") {
          // vm.geoJsonSource.source.data = mapgeoJson; //从本地加载geojson
          vm.wmsArrs[0].wmsLayer.paint["raster-opacity"] = 0;
          vm.wmsArrs[1].wmsLayer.paint["raster-opacity"] = 1;
          //隐藏卫星图，显示geojsonlayer
          // vm.wmsLayer.paint["raster-opacity"] = 0;
        } else {
          vm.geoJsonSource.source.data = {
            type: "FeatureCollection",
            features: []
          };
          //显示卫星图，隐藏geojsonlayer
          // vm.wmsLayer.paint["raster-opacity"] = 1;
          vm.wmsArrs[0].wmsLayer.paint["raster-opacity"] = 1;
          vm.wmsArrs[1].wmsLayer.paint["raster-opacity"] = 0;
        }
      });
    },
    //测距时用
    isDistance() {
      //是否测距
      this.isRange = !this.isRange;
      if (!this.isRange) {
        this.rmDistance();
      }
    },
    rmDistance() {
      //清除数据或结束测距
      this.lnglatArr = [];
      this.dotsArr = [];
      this.finallnglats = [];
      this.distances = [];
      this.$store.dispatch("distances/addLines", []);
      this.$store.dispatch("distances/addDots", []);
      this.$store.dispatch("distances/addDistances", []);
    },
    //划定区域用
    areaDivision() {
      this.isDivision = !this.isDivision;
      if (!this.isDivision) {
        this.$store.dispatch("distances/addDivision", {});
      }
    },
    areaDanger() {
      this.isDanger = !this.isDanger;
      if (!this.isDanger) {
        this.rmDistance();
      }
    },
    callAndroid() {
      var setInter;
      // console.log("count:" + this.count);
      setInter = setInterval(() => {
        this.count += 1;
        if (this.count > 6) {
          clearInterval(setInter);
          this.count = 0;
        } else {
          let finalTracks = _.nth(this.carTracks, this.count);
          this.$store.dispatch("cartracks/setCarCoor", finalTracks);
        }
      }, 3000);
      window.android.jsAndroid("结束");
    },
    callJsFun(str) {
      this.callback = str;
      // this.$store.dispatch("cartracks/setCarCoor", coor);
    },
    addDanger() {
      let dangerForm = {
        highriskareaname: "高风险名称",
        detailedlocation: "高风险详细位置",
        highriskareadetailedlist: [
          [121.46242658520003, 30.79393178321041],
          [121.46731256625884, 30.79570619463575],
          [121.46917310113832, 30.79193432728799],
          [121.46419462802294, 30.79015560326901],
          [121.46242658520003, 30.79393178321041]
        ]
      };
      this.$http.post("BASF11101/insert", this.ruleForm, res => {
        // console.log(res);
      });
    },
    polyDrawEnd() {
      this.isDrawPoly = false;
    },
    rmPolygon() {
      //清除数据或重新绘制
      this.lnglatArr = [];
      this.dotsArr = [];
      this.finallnglats = [];
      this.polygonLnglats = [];
      this.$store.dispatch("distances/addLines", []);
      this.$store.dispatch("distances/addDots", []);
      this.$store.dispatch("distances/addPolygon", []);
      this.isDrawPoly = true;
    },
    isShowWms() {
      this.wmsShow = !this.wmsShow;
      if (!this.wmsShow) {
        this.wmsLayer.paint["raster-opacity"] = 0;
      } else {
        this.wmsLayer.paint["raster-opacity"] = 1;
      }
    },
    isShowSatellite() {
      this.satelliteShow = !this.satelliteShow;
      if (this.satelliteShow) {
        this.mapOptions.mapStyle =
          "mapbox://styles/mapbox/satellite-streets-v10";
      } else {
        this.mapOptions.mapStyle = "mapbox://styles/mapbox/light-v10";
      }
    }
  },

  watch: {}
};
</script>
<style scoped>
.map {
  height: 100%;
}
.android-test {
  position: absolute;
}
</style>